import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hm_show_flutter/api/service/user_service.dart';
import 'package:hm_show_flutter/config/app_build.dart';
import 'package:hm_show_flutter/constant/string.dart';
import 'package:hm_show_flutter/entity/company.dart';
import 'package:hm_show_flutter/entity/init_entity.dart';
import 'package:hm_show_flutter/entity/login_entity.dart';
import 'package:hm_show_flutter/style/style.dart';
import 'package:hm_show_flutter/utils/navigator_util.dart';
import 'package:hm_show_flutter/utils/shared_preferences_util.dart';
import 'package:hm_show_flutter/utils/toast_util.dart';
import 'package:hm_show_flutter/widgets/support_view.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  ///是否隐藏密码
  bool isObscure = true;

  TextEditingController _accountTextControl = TextEditingController();
  TextEditingController _passwordTextControl = TextEditingController();
  UserService userService = UserService();
  LoginEntity userEntity;

  bool isDisplayRegister;
  String strAgreement;

  @override
  void initState() {
    super.initState();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown
    ]).then((result){
    });
    SharedPreferencesUtils.getInit().then((model) {
      InitData data = model;
      if (data != null) {
        setState(() {
          isDisplayRegister = data.registerDisplay;
          strAgreement = data.privacyProtocolUrl;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    final register = GestureDetector(
      onTap: () {
        NavigatorUtils.goRegister(context);
      },
      child: Container(
        alignment: Alignment.centerRight,
        padding: EdgeInsets.only(right: 10, top: 40),
        child: Text("注册", style: TextStyle(fontSize: 14)),
      ),
    );
    final logo = Container(
      width: 80,
      height: 80,
      child: ClipRRect(
        //圆角图片
        borderRadius: BorderRadius.circular(6),
        child: Image.asset(AppBuild.app_ic_ion),
      ),
    );

    final email = TextFormField(
      keyboardType: TextInputType.emailAddress,
      autofocus: false,
      inputFormatters: [
        WhitelistingTextInputFormatter(RegExp("[a-z,A-Z,0-9]")), //限制只允许输入字母和数字
        LengthLimitingTextInputFormatter(11), //限制输入长度不超过8位
      ],
      controller: _accountTextControl,
      decoration: InputDecoration(
        hintText: Strings.LOGIN_HINT_ACCOUNT,
        hintStyle: TextStyle(fontSize: 12),
        prefixIcon: Icon(
          Icons.account_circle,
          size: 18,
        ),
        contentPadding: EdgeInsets.fromLTRB(15.0, 8.0, 15.0, 8.0),
        focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(32.0),
            borderSide: BorderSide(width: 1, color: AppColors.mainColor)),
        enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(32.0),
            borderSide: BorderSide(width: 1, color: AppColors.grey)),
      ),
    );

    final password = TextFormField(
      autofocus: false,
      obscureText: isObscure,
      inputFormatters: [
        WhitelistingTextInputFormatter(RegExp("[a-z,A-Z,0-9]")), //限制只允许输入字母和数字
        LengthLimitingTextInputFormatter(11), //限制输入长度不超过8位
      ],
      controller: _passwordTextControl,
      decoration: InputDecoration(
        hintText: Strings.LOGIN_HINT_PASSWORD,
        hintStyle: TextStyle(
          fontSize: 12,
        ),
        prefixIcon: Icon(
          Icons.lock,
          size: 18,
        ),
        suffixIcon: GestureDetector(
          child: Icon(
            isObscure ? Icons.visibility : Icons.visibility_off,
            size: 18,
          ),
          onTap: () {
            setState(() {
              isObscure = !isObscure;
            });
          },
        ),
        contentPadding: EdgeInsets.fromLTRB(15.0, 8.0, 15.0, 8.0),
        focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(32.0),
            borderSide: BorderSide(width: 1, color: AppColors.mainColor)),
        enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(32.0),
            borderSide: BorderSide(width: 1, color: AppColors.grey)),
      ),
    );

    final agreement = Container(
      padding: EdgeInsets.only(top: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text("登录即表示您同意", style: TextStyle(fontSize: 14)),
          GestureDetector(
            onTap: _agreement,
            child: Text(
              "《隐私安全指引》",
              style: TextStyle(color: AppColors.mainColor, fontSize: 14),
            ),
          )
        ],
      ),
    );

    final loginButton = Container(
      width: double.infinity,
      padding: EdgeInsets.only(left: 24, right: 24),
      child: RaisedButton(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(24),
        ),
        onPressed: _login,
        padding: EdgeInsets.all(13),
        color: AppColors.mainColor,
        child: Text(Strings.LOGIN,
            style: TextStyle(
              color: Colors.white,
            )),
      ),
    );

    DateTime _lastPopTime;
    _doubleBack() async {
      // 点击返回键的操作
      if (_lastPopTime == null ||
          DateTime.now().difference(_lastPopTime) > Duration(seconds: 2)) {
        _lastPopTime = DateTime.now();
        ToastUtil.showToast('再按一次退出');
      } else {
        _lastPopTime = DateTime.now();
        // 退出app
        await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
      }
    }

    return WillPopScope(
      child: Scaffold(
        backgroundColor: Colors.white,
        body: Center(
          child: Column(
            children: <Widget>[
              isDisplayRegister ? register : Container(),
              SizedBox(height: 60.0),
              logo,
              SizedBox(height: 48.0),
              Padding(
                padding: EdgeInsets.only(left: 24, right: 24),
                child: email,
              ),
              SizedBox(height: 8.0),
              Padding(
                padding: EdgeInsets.only(left: 24, right: 24),
                child: password,
              ),
              SizedBox(height: 35.0),
              loginButton,
              strAgreement == null ? Container() : agreement,
              Expanded(child: Container()),
              SupportView()
            ],
          ),
        ),
        resizeToAvoidBottomPadding: false,
      ),
      onWillPop: _doubleBack,
    );
  }

  _login() {
    String _account = _accountTextControl.text.toString();
    String _password = _passwordTextControl.text.toString();
    if (_account.isNotEmpty && _password.isNotEmpty) {
      userService.login(_account, _password, (success) {
        print(success);
        userEntity = success;
        _saveUserInfo();
        ToastUtil.showToast(Strings.LOGIN_SUCCESS);
        NavigatorUtils.goMallMainPage(context);
      }, (onFail) {
        if (onFail != null) {
          print(onFail);
          ToastUtil.showToast(onFail);
        }
      });
    } else {
      ToastUtil.showToast(Strings.LOGIN_TIP);
    }
  }

  _agreement() {
    NavigatorUtils.goWebView(context, "隐私安全指引", strAgreement);
  }

  _saveUserInfo() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    SharedPreferencesUtils.token = userEntity.data.token;
    await sharedPreferences.setString(Strings.token, userEntity.data.token);

    SharedPreferencesUtils.saveCompany(CompanyModel(
        name: userEntity.data.user.companyName,
        id: userEntity.data.user.companyId));
    SharedPreferencesUtils.saveUser(userEntity.data.user);
  }
}
